package com.tungse.study.rpc.framework.protocol;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tungse.study.rpc.framework.entity.Invocation;
import com.tungse.study.rpc.framework.register.LocalRegister;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Tungse
 */
public class HttpServletHandler {
    public String handler (HttpServletRequest req, HttpServletResponse resp) {
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();

            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();

            Class<?> service = LocalRegister.getService(interfaceName);
            Method method = service.getMethod(methodName, invocation.getParameterTypes());
            Object result = method.invoke(service.newInstance(), invocation.getArgs());
            return new ObjectMapper().writeValueAsString(result);
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
